package com.album.activity.pageView;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Entity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;

import com.album.R;
import com.album.activity.MessageDialog;
import com.album.activity.SetstateManager; 
import com.album.activity.adapter.MyPhotoAdapter;
import com.album.activity.page.Page;
import com.album.activity.page.PageManager;
import com.album.bean.ErrorInfo;
import com.album.bean.ImageBean;
import com.album.bean.PicinfoList;
import com.album.bean.RondomUser;
import com.album.http.HttpRequest;
import com.album.task.AddFriendTask;
import com.album.task.DownImageTask;
import com.album.task.GetPicinfolistTask;
import com.album.task.GetRandomPicinfolistTask;
import com.album.task.GetUsersRandom;
import com.album.task.ICallBack;
import com.album.task.Task;
import com.album.utils.AndroidUtils;
import com.album.utils.CommonUtil;
import com.album.utils.Config;
import com.album.utils.MyLog;
import com.album.utils.down.AsyncImageLoader;
import com.album.utils.down.ImageUtil;
import com.album.utils.down.MyImageAdapter;
import com.album.utils.down.ImageAndText;
import com.album.utils.down.AsyncImageLoader.ImageCallback;
import com.album.utils.down.ImageAndTextListAdapter;
import com.google.gson.Gson;

public class CasualLookView extends Page{
	private static String TAG = "CasualLookView";
	 
	/**
	 * 好友头像
	 */ 
	private ListView casualListView;
	private HorizontalScrollView scrollView;
	private Gson gson;

	private static final int HENDLER = 110;
	private static final int ROMDOMUSER_INFO = 111;
	private static final int ROMDOMUSER_FAIL = 112;
	private static final int ROMDOMUSER_IMAGE_INFO = 113;
	private static final int ROMDOMUSER_IMAGE_FAIL = 114;
	private static final int ROMDOMUSER_NO = 115;
	private static final int PICINFOLIST_RE_MYPTO_IMAGE = 117;
	private static final int PICINFOLIST_DOWN_IMAGE_FAIL = 118;
	private static final int PICINFOLIST_INFO = 119;
	private static final int PICINFOLIST_INFO_FAIL = 200;
	private static final int PICINFOLIST_INFO_NOT = 222;
	private static final int LOGING_USERINFO = 254;
	private static final int LOGING_USERIMAGELIST = 255;
	private static final int LOGING_HENDLER = 256;

	
	
	private static final int ADD_FRIENDS = 201;
	private static final int ADD_FRIENDS_FAIL = 202;

	private static final int TIME_OUT = 11;
	private static final int INTENT_ERROR = 12;
	private static final int HTTP_ERROR = 13;
	private ProgressDialog dialog_1;
	private Context ctx;
	private boolean loding_view_flgs = false;	//刷新view 避免重复
	//好友图片url 
	/*
	 * 存放用户头像、昵称、时间、相片
	 */
	private List<RondomUser> userRanList = new ArrayList<RondomUser>();
	private ListAdapter adapterTest;
	
	public CasualLookView(PageManager manager) {
		super(manager);
	}
	@Override
	public View getView() {
		Log.i(TAG, "@Override getView");
		return casualListView;
	}	
	@Override
	public void onCreate(Object extra) {
		super.onCreate(extra);
		 
		if(userRanList != null && userRanList.size()>0){
			userRanList.clear();
		}  
		ctx = manager.getContext();
		SetstateManager.setBacktoState(CasualLookView.class,manager);
		SetstateManager.setRefresState(CasualLookView.class,manager);
		
		if(SetstateManager.infoList!= null&&SetstateManager.infoList.size()>0){
			SetstateManager.infoList.clear();
		} 
		
		if(!loding_view_flgs){
			casualListView = new ListView(ctx);
			casualListView.setBackgroundColor(Color.BLACK);
			casualListView.setCacheColorHint(0x00000000);
			casualListView.setScrollbarFadingEnabled(false);
			casualListView.setVerticalScrollBarEnabled(true);
			adapterTest = new ListAdapter(manager.getContext());
		    casualListView.setAdapter(adapterTest);
		}
		
	    
       //随机获取好友列表 
        getRandomFriends(); 

		if(!loding_view_flgs)
			loding_view_flgs = true;
		
			MyLog.debug(getClass(), "===================loding_view_flgs====================:"+loding_view_flgs);
	}
	/**
	 * 获取好友列表
	 * @author Administrator
	 */
	private String getRandomFriends(){

		dialog_1 = ProgressDialog.show(ctx, "",ctx.getText(R.string.get_random_frineds), true);
		dialog_1.setCancelable(true);
		
		// loding userinfo list...
		Thread thread = new Thread(){
			@Override
			public void run() {
				String strUrl =Config.TyHttp + Config.TyUserHttp+"getusers?count=5&rows=5";
				// TODO Auto-generated method stub
				String rspString = HttpRequest.sendDataPost(ctx,strUrl, null,null);
				List<String> listUserImageUrl= new ArrayList<String>();
				try {
					MyLog.info(getClass(), "jsonData:" + rspString);
					rspString = "[" + rspString + "]";
					JSONArray array = new JSONArray(rspString.toString());
					JSONArray array_data;
					JSONObject obj = array.getJSONObject(0);
					if (obj.getBoolean("msg")) {
						String res_data = obj.getString("data");
//						MyLog.info(getClass(), "data:" + res_data.toString());
						if("[]".equals(res_data.toString())){
							handler.sendEmptyMessage(ROMDOMUSER_NO); 
						}
						array_data = new JSONArray(res_data.toString()); 
						int ar_length = array_data.length();
						for (int i = 0; i <ar_length ; i++) {
							RondomUser user = new RondomUser();
							JSONObject obj_data = array_data.getJSONObject(i);
							String passport = obj_data.getString("passport");
							user.setPassport(passport);
							user.setNick(obj_data.getString("nick"));
							user.setHead_path(obj_data.getString("icon"));
							userRanList.add(user);
							MyLog.debug(getClass(), "___________________好友用户：" + passport);

							listUserImageUrl.add(passport);	//拿好友图片
							 
							Message heandms = new Message();
							heandms.obj=user;
							heandms.what = HENDLER; 
							//sendMessageAtFrontOfQueue
							handler.sendMessageAtFrontOfQueue(heandms);	//立即发送Message到队列，而且是放在队列的最前面  
						}
						if (dialog_1 != null && dialog_1.isShowing()){
							dialog_1.dismiss();
						}
						
						Message ms = new Message();
						ms.obj=listUserImageUrl;
						ms.what = LOGING_USERIMAGELIST;
						handler.sendMessage(ms);
						
					} else {
						MyLog.debug(getClass(), "————————————好友失败————————————");
					}
				} catch (Exception e) { 
				}
			}
		};
		thread.setDaemon(true);
		thread.start();
	
		return null;
	}
	/**
	 * 获取相册列表
	 */
	private void getPicinfolist(final String username) {
		MyLog.debug(getClass(), "__________________getPicinfolist username:"+username);
		if (gson == null) {
			gson = new Gson();
		}
		Task task = new GetRandomPicinfolistTask(ctx,username, null,
				new ICallBack() {
					@Override
					public void CallBack(String imageUrl, Bitmap bm) {
					}
					@Override
					public void CallBack(String rspString) {
						// TODO Auto-generated method stub
						Map<String, List<ImageBean>> imagelistMap = new HashMap<String, List<ImageBean>>();
						HashMap<String, List<String>> imageIdMap = new HashMap<String, List<String>>();
//						MyLog.info(getClass(), "jsonData:" + rspString);
						rspString = "[" + rspString + "]";
						JSONArray array;
						JSONArray array_data;
						List<PicinfoList> picinfoList;
						List<ImageBean> imangeList;
						List<String> imageId;
						try {
							int j=0; //获取单个好友图片个数，默认为4张图片
							picinfoList = new ArrayList<PicinfoList>();
							imangeList = new ArrayList<ImageBean>();
							imageId = new ArrayList<String>();
							array = new JSONArray(rspString.toString());
							JSONObject obj = array.getJSONObject(0);
							if (obj.getBoolean("msg")) {
								String res_data = obj.getString("data");
								if(!"[]".equals(res_data.toString())){
//									MyLog.info(getClass(), data:" + res_data.toString());
									array_data = new JSONArray(res_data.toString());
									int length = array_data.length();
									for (int i = 0; i < length; i++) {
										JSONObject obj_data = array_data.getJSONObject(i);
//										MyLog.info(getClass(),"exif:" + obj_data.toString());
										PicinfoList info = new PicinfoList();
//										info.setFileid(obj_data.getString("fileid"));
										info.setId(obj_data.getString("id"));
										info.setPassport(obj_data.getString("passport"));
//										info.setPublic_(obj_data.getString("public"));
//										info.setTypeid(obj_data.getString("typeid"));
										info.setUpload_time(obj_data.getString("upload_time"));
//										info.setTitle(obj_data.getString("title"));
//										info.setContent(obj_data.getString("content"));
//										info.setViews(obj_data.getString("views"));
//										info.setScore(obj_data.getString("score"));
//										info.setBlock(obj_data.getString("block"));
//										info.setArea(obj_data.getString("area"));
//										info.setCoordinate(obj_data.getString("coordinate"));
										info.setPath_image(obj_data.getString("web_path"));
//										info.setHash_code(obj_data.getString("hash_code"));
//										MyLog.info(getClass(), "web_path:" + info.getPath_image());
										//ProviderUtil.insertOrUpdatePicinfoList(manager.getContext(), info);
										picinfoList.add(info);
										if(j!=4){
											ImageBean imageBean = new ImageBean();
											if(info.getPath_image()!=null){
												String filename = info.getPath_image().substring(info.getPath_image().lastIndexOf("/")+1);
												filename = filename.substring(0, filename.length()-4)+"_75_75."+filename.substring(filename.length()-3,filename.length());
												
												String imageUrul = Config.TyDownHttp+info.getPassport()+"/"+filename;
//												MyLog.info(getClass(),"random imageUrul:" + imageUrul);
												imageBean.setImageUrl(imageUrul);
												imageBean.setPirId(info.getId());
												imangeList.add(imageBean);
												//imageId.add(info.getId());
												j++;
											}
										}
										 
										imagelistMap.put(username, imangeList);
										//imageIdMap.put(username, imageId);
										//SetstateManager.setPicIdMapState(imageIdMap);
									} 
								}
								else{	// not 
									//imagelistMap.put(username, new ArrayList());
//									Message ms = new Message();
//									ms.what = PICINFOLIST_INFO_NOT;
//									ms.obj = username;
//									handler.sendMessage(ms);
								}
								Message ms = new Message();
								ms.what = PICINFOLIST_INFO_NOT;
								ms.obj = imagelistMap;
								handler.sendMessage(ms);
								
							} else {
								PicinfoList info = new PicinfoList();
								info.setErrCode(obj.getString("errCode"));
								Message ms = new Message ();
								ms.what = PICINFOLIST_INFO_FAIL;
								ms.obj = info;
								handler.sendMessage(ms);
							}
							
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
					@Override
					public void TimeOut() {
						//网络超时处理
						handler.sendEmptyMessage(TIME_OUT);
					}
					@Override
					public void HttpError(int errorCode) {
						// TODO Auto-generated method stub
						handler.sendEmptyMessage(INTENT_ERROR);
					}
				});
		task.doTask(task);
	}
    /**
     * 添加好友
     * @author Administrator
     *
     */
	private void addFriend(String friendname){
		Task task = new AddFriendTask(ctx,CommonUtil.getUserName(ctx),friendname,new ICallBack() {
			
			@Override
			public void TimeOut() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void HttpError(int errorCode) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void CallBack(String imageUrl, Bitmap bm) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void CallBack(String rspString) {
				try {
					MyLog.info(getClass(), "jsonData:" + rspString);
					rspString = "[" + rspString + "]";
					JSONArray array = new JSONArray(rspString.toString());
					JSONObject obj = array.getJSONObject(0);
					if (obj.getBoolean("msg")) {
						Message ms = new Message();
						ms.what = ADD_FRIENDS;
						handler.sendMessage(ms);
					} else {
						Message ms = new Message();
						ms.what = ADD_FRIENDS_FAIL;
						handler.sendMessage(ms);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
		task.doTask(task);
	}
    /**
     * 处理ui界面
     */
    private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case LOGING_USERIMAGELIST:
					List<String> userNamelist =(List<String>)msg.obj;
					new loadingUserImage().execute(userNamelist);
					break;
				case HENDLER:
//					Object[] reObj = (Object[])msg.obj;
//					RondomUser bean = (RondomUser)reObj[0];
//					Bitmap bitmap = (Bitmap)reObj[1];

					RondomUser bean = (RondomUser)msg.obj;
					adapterTest.setDataUserSetChange(bean);
					break;
				case LOGING_HENDLER:
					List<RondomUser> rondomUserlist =(List<RondomUser>)msg.obj;
					MyLog.debug(getClass(), "________好友Rond：" + rondomUserlist.size());
					new loadingUserRondom().execute(rondomUserlist);
					break;
				case ROMDOMUSER_INFO:
					RondomUser user=(RondomUser)msg.obj;
					adapterTest.setDataUserSetChange(user);
						MyLog.debug(getClass(), "___________________好友用户：" + user.getPassport());
						getPicinfolist(user.getPassport()); 
						if (dialog_1 != null && dialog_1.isShowing())
							dialog_1.dismiss();
					
					break;
				case ROMDOMUSER_FAIL: //获取用户信息失败
					RondomUser infoFail = (RondomUser) msg.obj;
					MessageDialog.showToast(manager.getContext(), false,
							ErrorInfo.errorMap.get(infoFail.getErrCode()));
					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					break;
				case ROMDOMUSER_NO: //获取用户信息失败
					MessageDialog.showToast(manager.getContext(), false,
							manager.getContext().getString(R.string.no_random_friend));
					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					break;
				case PICINFOLIST_INFO:
						//下载随便看看相片  
//					ImageUrlBean bean = (ImageUrlBean)msg.obj;
//					String userName= bean.getUserName();
//					List<String> imageUrllist = bean.getUrlList(); 
//					if(imageUrllist!=null){
////						MyLog.debug(getClass(), "userName:"+ userName+" imageUrlSize:"+imageUrllist.size());
//						adapterTest.setDataSetChangedImageUrl(userName,imageUrllist);
//					}
								//刷新界面
					break;
				case PICINFOLIST_INFO_NOT:
					Map<String, List<ImageBean>> imagelistMap =(HashMap<String, List<ImageBean>>)msg.obj;
					List<ImageBean> imageUrlList = null ;
					for(Entry<String, List<ImageBean>> entry: imagelistMap.entrySet()) {  
						imageUrlList = entry.getValue();
						   MyLog.info(getClass(), ">>>>>>>>>>>>>>>>>>>>>userName:"+entry.getKey()+"-----imageListSize--:"+entry.getValue().size());
					}  
//					String username = msg.obj.toString();
//						adapterTest.setDataSetChangedImageUrl(username,new ArrayList<String>());
					
					adapterTest.setDataSetChangedImageUrl(imagelistMap);
					break;
				case PICINFOLIST_INFO_FAIL:// 获取相册失败
					PicinfoList picInfo_fail = (PicinfoList)msg.obj;
					MessageDialog.showToast(manager.getContext(), false,ErrorInfo.errorMap.get(picInfo_fail.getErrCode()));
					break;
				case PICINFOLIST_RE_MYPTO_IMAGE:
					//做图片显示操作
//					Bitmap bm = (Bitmap)msg.obj;
//					//刷新界面
//					adapterTest.notifyDataSetChanged();
//					casualListView.setAdapter(adapterTest);
					break;
				case PICINFOLIST_DOWN_IMAGE_FAIL://下载图片失败
					MessageDialog.showToast(manager.getContext(), false, manager.getContext().getString(R.string.imagedown_doing_fail));
					break;
				case ADD_FRIENDS://添加好友成功
					MessageDialog.showToast(manager.getContext(), false, manager.getContext().getString(R.string.add_friend));
					break;
				case ADD_FRIENDS_FAIL://添加好友失败
					MessageDialog.showToast(manager.getContext(), false, manager.getContext().getString(R.string.add_friend_fail));
					break;
				case TIME_OUT://超时
					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					MessageDialog.showToast(manager.getContext(), false, manager.getContext().getString(R.string.int_timeout));
					break;
				case INTENT_ERROR://网络错误
					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					MessageDialog.showToast(manager.getContext(), false, manager.getContext().getString(R.string.int_error));
					break;
					}
			} catch (Exception e) {
			    e.printStackTrace();
			}
			}
	};
	public Bitmap getBitmap(RondomUser info ){
				Bitmap bm =null;
//				MyLog.info(getClass(), "随便看看头像名字："+info.getHead_path());
				String url = Config.TyDownHttp+CommonUtil.getHeadImage(info.getPassport(),info.getHead_path());
//					bm=	CommonUtil.loadBitMap(ctx, url);//下载头像
//					MyLog.info(getClass(), "随便看看头像："+bm);
				try {
					bm = ImageUtil.getBitmapFromUrl(url);
				} catch (Exception e) { return null;
				}
				if(bm == null){
					InputStream is = manager
							.getContext()
							.getResources()
							.openRawResource(
									R.drawable.inithead);
					bm = BitmapFactory.decodeStream(is);
				}
			
		return bm;
	}
    public class ViewHolder{
    	 ImageView userHead;
			TextView userName;
			TextView time;
			ImageView lookpto;
			ImageView addfriend;
			GridView gridView;
			LinearLayout Layout;
			LinearLayout imageLayout;	
			LinearLayout layout_center; 
    }
    
    class ImageAdapter extends BaseAdapter{  
    	  //声明Context   
    	  private Context context;  
    	  private int i=0;
    	  //图片源数组   
    	  private Integer[] imageInteger = new Integer[4]; 
    	  
    	  public ImageAdapter(Context c,int i){  
     	     this.context = c;   
    	     if(i==1){
    	    	 Integer[] imageInteger = new Integer[]{  
    	    	         R.drawable.loading,  
    	    	         R.drawable.loading,  
    	    	         R.drawable.loading,  
    	    	         R.drawable.loading};
    	    	 		this.imageInteger = imageInteger;
    	     }else{
    	    	 Integer[] imageInteger2 = new Integer[]{  
    	    		 R.drawable.icon,  
         	         R.drawable.icon,  
         	         R.drawable.icon,  
         	         R.drawable.icon};
    	    	 		this.imageInteger = imageInteger2;
    	     }
    	  }  
    	 
    	  @Override 
    	  //获取图片的个数  
    	  public int getCount() {  
    	     return imageInteger.length;  
    	  }  
    	 
    	  @Override 
    	  //获取图片在库中的位置  
    	  public Object getItem(int position) {  
    	 
    	     return position;  
    	  }  
    	 
    	  @Override 
    	  //获取图片在库中的位置  
    	  public long getItemId(int position) {  
    	     // TODO Auto-generated method stub  
    	     return position;  
    	 }  
    	 
    	  @Override 
    	  public View getView(int position, View convertView, ViewGroup parent) {  
             final ImageView imageView;           
             if (convertView == null) {      
                 imageView=new ImageView(context);
                 imageView.setLayoutParams(new GridView.LayoutParams(70, 70));  
                 imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);   
                 convertView = imageView;   
        	     imageView.setImageResource(imageInteger[position]);
             } 
    	     //设置布局 图片128x192显示   
    	     return convertView;  
    	  }  
    	}  
	 public class ListAdapter extends BaseAdapter{
		 
		 	private String imageUrl= "http://img2.vipshop.com/upload/merchandise/4787/ANTA-1033383-2-5.jpg";
	    	private Context mContext;
	        private AsyncImageLoader imageLoader;
	        //默认头像 
	        private Drawable defaultDrawable = null;	
	        //好友图片Url
	        private List<Map<String, List<ImageBean>>> user_imagelist = new ArrayList<Map<String, List<ImageBean>>>();
	        
	        //用户信息
	    	private List<RondomUser> userRanList = new ArrayList<RondomUser>(); 
	    	
	    	private ListAdapter(Context context){
	    		mContext = context; 
	    		if(defaultDrawable==null){
	    			defaultDrawable =  mContext.getResources().getDrawable(R.drawable.inithead);
	    		}
	    	}
			public void setDataSetChangedImageUrl(Map<String, List<ImageBean>> imageUrl_list){
				user_imagelist.add(imageUrl_list);
		    	notifyDataSetChanged();
			}
			public void setDataUserSetChange(RondomUser user){ 
				userRanList.add(user);
		    	notifyDataSetChanged();
		    }
			
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;  
			if (convertView == null) {
				imageLoader = new AsyncImageLoader();
				holder = new ViewHolder();  
				LayoutInflater inflater  = LayoutInflater.from(mContext); 
				convertView = inflater.inflate(R.layout.casual_image_list, null);
				holder.Layout = (LinearLayout) convertView .findViewById(R.id.LinearLayout_list);
				holder.userHead = (ImageView) convertView .findViewById(R.id.image_head);
				holder.userName = (TextView) convertView .findViewById(R.id.user_name);
				holder.time = (TextView) convertView .findViewById(R.id.user_time);
				holder.lookpto = (ImageView) convertView .findViewById(R.id.lookpto);
				holder.addfriend = (ImageView) convertView .findViewById(R.id.addfriend);
				holder.layout_center =(LinearLayout)convertView .findViewById(R.id.layout_center); 
				holder.gridView = (GridView)convertView.findViewById(R.id.gridView);
				holder.gridView.setGravity(Gravity.CENTER);// 位置居中  
				convertView.setTag(holder); 
			}else{
				holder = (ViewHolder) convertView.getTag();
			} 
			try {
				
				//设置头像
//				if (headBmList != null && headBmList.size() > 0) {
//					Bitmap bm = headBmList.get(position);
//					if(bm!=null){
//						bm = Bitmap.createScaledBitmap(bm, 40, 40, true);// 预先缩放，避免实时缩放，可以提高更新率
//						holder.userHead.setImageBitmap(bm);
//					}else{
//						holder.userHead.setImageBitmap(defaultHeadbm);
//					}
//				} 
				String ranImageUrl = userRanList.get(position).getHead_path();
				MyLog.debug(getClass(), "ranImageUrl:"+ranImageUrl);
				
				if(ranImageUrl!=null && ranImageUrl!=""){	//解析JSON 此路径为 null
					defaultDrawable = imageLoader.loadDrawable(ranImageUrl, new ImageCallback() {  

	                     public void imageLoaded(Drawable imageDrawable, String imageUrl) {  
	                         if(imageDrawable!=null)
	                        	 holder.userHead.setImageDrawable(imageDrawable);  
	                     }  
	                 });   
				}
				
				holder.userHead.setImageDrawable(defaultDrawable);
				 
				if(user_imagelist!=null && user_imagelist.size()>0){ 
					Map<String, List<ImageBean>> mapBean = user_imagelist.get(position);
					List<ImageBean> imageBeanlist=null;
					String userName=null ;
					for(Entry<String, List<ImageBean>> entry: mapBean.entrySet()) {  
						userName = entry.getKey();
						imageBeanlist = entry.getValue();
					}  
//					SetstateManager.setUsernameList(userName);
					int imageSize = imageBeanlist.size(); 
//					MyLog.debug(getClass(), "position:"+position+" userName:"+userName+" imageList:"+imageSize);
					
					MyImageAdapter myimggeAdapter = new MyImageAdapter(mContext, imageBeanlist);
					holder.gridView.setAdapter(myimggeAdapter);
//					imageAdapter.notifyDataSetChanged(); 
						
					holder.gridView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view, int pic, long id) {
						
						// Eugene:调用图片编辑器
						MyLog.info(getClass(), "Eugene: Invoking PicInfoView");
						//SetstateManager.setPicUserState(userName);
						//SetstateManager.setPicListState(SetstateManager.infoList.get(pic).getId());
						try {
							manager.activePage(PicinfoView.class, null);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}});
				}
				if(SetstateManager.imageIdMapList!=null && SetstateManager.imageIdMapList.size()>0){ 
					Map<String, List<String>> map = SetstateManager.imageIdMapList.get(position);
					List<String> imageId=null;
					String userName=null ;
					for(Entry<String, List<String>> entry: map.entrySet()) {  
						userName = entry.getKey();
						imageId =entry.getValue();
						SetstateManager.setUsernameList(userName); 
					}  
				}

			}catch (Exception e) { MyLog.debug(getClass(), e.getMessage()); 
			}catch(OutOfMemoryError er){ return null;
			} 
		
			//长按操作
			holder.userHead.setOnLongClickListener(new View.OnLongClickListener() {
					
				@Override
				public boolean onLongClick(View v) { 
					MyLog.debug(getClass(), "onLongClick...");
					holder.layout_center.setVisibility(View.VISIBLE);
					return true;
				}
			});
			holder.userName.setOnLongClickListener(new View.OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					holder.layout_center.setVisibility(View.VISIBLE);
					return true;
				}
			});
			holder.Layout.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Log.i(TAG, "单击消失");
						if(holder.layout_center.getVisibility()==View.VISIBLE)
							holder.layout_center.setVisibility(View.GONE); 
					}
				});
				//点击添加好友
			holder.addfriend.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						//调用添加好友
					if (CommonUtil.isUserLogin(ctx)) {

						// TODO Auto-generated method stub
						// 删除操作
						new AlertDialog.Builder(ctx)
						        .setTitle(R.string.label_t)
								.setMessage(R.string.add_msg)
								.setPositiveButton(R.string.label_ok,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialoginterface,
													int i) {
												Log.i(TAG, "确定添加关系");
												try {
													MyLog.info(getClass(), "addfriend:"+userRanList.get(position).getPassport());
													addFriend(userRanList.get(position).getPassport());
												} catch (Exception e) {
													e.printStackTrace();
												}
												// 按钮事件
											}
										})
								.setNegativeButton(R.string.label_cancel,
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int whichButton) {
												// 取消按钮事件
												Log.i(TAG, "取消解除关系");
											}
										}).show();
					} else {
						try {
							manager.activePage(UserLoginView.class, null);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					}
				});
				//点击查看相片
			holder.lookpto.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						try {
							manager.activePage(PicinfoView.class, null);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			
				//设置昵称
			    if (userRanList != null && userRanList.size() > 0){
			    String nick = userRanList.get(position).getNick();
				if(nick!=null &&! "".equals(nick))
					holder.userName.setText(userRanList.get(position).getNick());
			    }else{
			    	String username = userRanList.get(position).getPassport();
			    	if(!"pconline".equals(username))
			    	holder.userName.setText(userRanList.get(position).getPassport().substring(0,7)+"****");
			    	else
			    		holder.userName.setText(userRanList.get(position).getPassport());
			    }
				//设置时间
					holder.time.setText("9月1日");
				//设置四张相片
			return convertView;
		} 
//		public void setDataSetChangedBitmap(Bitmap bitmap){ 
//			userRanList.add(bitmap);
//	    	notifyDataSetChanged();
//	    }
//		
		@Override
		public int getCount() {
			return (userRanList !=null && userRanList.size()>0) ? userRanList.size():0;  
		}
		@Override
		public Object getItem(int position) {
			return (userRanList !=null && userRanList.size()>0) ? userRanList.get(position): null; 
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		
	}
	 
	 //异步加载好友图片信息同时更新UI
	 class loadingUserImage extends AsyncTask<List<String>,Object,Integer>{ 
	 		
	 		int returnStatus=0;
	 		@Override
	 		protected Integer doInBackground(List<String>... params) {
	 			// TODO Auto-generated method stub
	 			try {  
	 				List<String> usernameList = params[0];
	 				
	 				for(String userName :usernameList ){
	 					String strUrl =Config.TyHttp + Config.TyPicHttp+"picinfolist?type="+"&passport="+userName
	 					+"&attribute=";
	 					String rspString = HttpRequest.sendDataPost(ctx,strUrl, null,null);
	 						Map<String, List<ImageBean>> imagelistMap = new HashMap<String, List<ImageBean>>();
							HashMap<String, List<String>> imageIdMap = new HashMap<String, List<String>>();
//							MyLog.info(getClass(), "jsonData:" + rspString);
							rspString = "[" + rspString + "]";
							JSONArray array;
							JSONArray array_data;
							List<PicinfoList> picinfoList;
							List<ImageBean> imangeList;
							List<String> imageId;
							try {
								int j=0; //获取单个好友图片个数，默认为4张图片
								picinfoList = new ArrayList<PicinfoList>();
								imangeList = new ArrayList<ImageBean>();
								imageId = new ArrayList<String>();
								array = new JSONArray(rspString.toString());
								JSONObject obj = array.getJSONObject(0);
								if (obj.getBoolean("msg")) {
									String res_data = obj.getString("data");
									if(!"[]".equals(res_data.toString())){
//										MyLog.info(getClass(), data:" + res_data.toString());
										array_data = new JSONArray(res_data.toString());
										int length = array_data.length();
										for (int i = 0; i < length; i++) {
											JSONObject obj_data = array_data.getJSONObject(i); 
											PicinfoList info = new PicinfoList(); 
											info.setId(obj_data.getString("id"));
											info.setPassport(obj_data.getString("passport")); 
											info.setUpload_time(obj_data.getString("upload_time"));
											info.setPath_image(obj_data.getString("web_path"));
											picinfoList.add(info);
											if(j!=4){
												ImageBean imageBean = new ImageBean();
												if(info.getPath_image()!=null){
													String filename = info.getPath_image().substring(info.getPath_image().lastIndexOf("/")+1);
													filename = filename.substring(0, filename.length()-4)+"_75_75."+filename.substring(filename.length()-3,filename.length());
													
													String imageUrul = Config.TyDownHttp+info.getPassport()+"/"+filename;
//													MyLog.info(getClass(),"random imageUrul:" + imageUrul);
													imageBean.setImageUrl(imageUrul);
													imageBean.setPirId(info.getId());
													imangeList.add(imageBean); 
													j++;
												}
											}
											imagelistMap.put(userName, imangeList);
										} 
									}
									int imageCount = imangeList.size();
									MyLog.debug(getClass(), "用户:"+userName+" 图片个数:"+imangeList.size());
									if(imageCount>0){
										publishProgress(imagelistMap);
									}else{
										imagelistMap.put(userName, new ArrayList<ImageBean>());
										this.publishProgress(imagelistMap);
									}
								} else {
									this.publishProgress(returnStatus);
								}
								
							} catch (JSONException e) { e.printStackTrace();
							}
	 				}
	 				
	 			} catch (OutOfMemoryError e) {
	 				e.printStackTrace();
	 				return 1;
	 			}
	 			return 0;
	 		}
	 		
	 		@Override
	 		protected void onProgressUpdate(Object... values) {
	 			// TODO Auto-generated method stub 
	 			if(values!=null){
	 				MyLog.debug(getClass(), "values:"+values[0]);
	 				Map<String, List<ImageBean>> imagelistMap =(HashMap<String, List<ImageBean>>)values[0];
					List<ImageBean> imageUrlList = null ;
					for(Entry<String, List<ImageBean>> entry: imagelistMap.entrySet()) {  
						imageUrlList = entry.getValue();
						   MyLog.info(getClass(), ">>>>>>>>>>>>>>>>>>>>>userName:"+entry.getKey()+"-----imageListSize--:"+entry.getValue().size());
					} 
					adapterTest.setDataSetChangedImageUrl(imagelistMap);
	 			}
	 		}
	 		@Override  
	 	    protected void onCancelled() {  
	 			super.onCancelled();  
	 	    }  
	 		 
	 		@Override
	 		protected void onPostExecute(Integer result) {
	 			// TODO Auto-generated method stub 
	 			if(result==0){ 
	 			}
	 		}
	 	}
	 
	 class loadingUserRondom extends AsyncTask<List<RondomUser>,Bitmap,Integer>{   
		 
		 @Override
		 protected Integer doInBackground(List<RondomUser>... params) {
			 List<RondomUser> RondomUserlist = params[0];
			 Bitmap bm =null;
			 InputStream is = manager
				.getContext()
				.getResources()
				.openRawResource(
						R.drawable.inithead);
			 for(RondomUser info : RondomUserlist){
				try {
					 MyLog.info(getClass(), "随便看看头像名字："+info.getHead_path());
					 if(info.getHead_path()!=null){
						 bm = CommonUtil.loadBitMap(ctx, Config.TyDownHttp+CommonUtil.getHeadImage(info.getPassport(),
									info.getHead_path()));//下载头像
							if(bm == null){
								bm = BitmapFactory.decodeStream(is);
							}
					 }
						this.publishProgress(bm);
				} catch (Exception e) { return -1;
				}
			 }
			 return 1;
		 }
		 
		 @Override
	 	 protected void onProgressUpdate(Bitmap... bitmap) {
//			 if(adapterTest!=null)
//				 adapterTest.setDataSetChangedBitmap(bitmap[0]);
		 }
		 
		 @Override  
	 	 protected void onCancelled() {  
	 		super.onCancelled();  
	 	 }  
	 		 
	 	 @Override
	 	 protected void onPostExecute(Integer result) {
	 		// TODO Auto-generated method stub 
	 	 }
	 }
}
